var dragging = false;
//TODO: nahradit classou !! -> manana
var celebrio = {
	"desktop" : {
		element : null,
		contextmenu : null,
		setElement : function(element) {
			celebrio.desktop.element = element;
		},
		getElement : function() {
			return celebrio.desktop.element;
		},
		getHeight : function() {
			return    $(window).height() -   celebrio.taskbar.getElement().height();
		},
		getWidth : function() {
			return    $(celebrio.desktop.element).width();
		},
		display : function(url) {
			id = celebrio.desktop.getElement();
			id.width(celebrio.desktop.getWidth());
			id.height(celebrio.desktop.getHeight());
			appImage = new Image ();
			appImage.onload = function() {
				$('#desktopBackground').remove();
				celebrio.image.stretch(appImage, $(window));
				$('<img src="'+url+'"  alt="'+url+'" width="'+innerWidth+'" height="'+innerHeight+'" id="desktopBackground" />').css({
				position: "absolute",
				zIndex:	-10,
				left: 0,
				top: 0
				}).appendTo("body");
			};
			appImage.src = url;
		},
		icons : null,
		setColor : function(color) {
			$("body").css("backgroundColor", color);
		},
        createIcons : function () {
            id = celebrio.desktop.getElement();
            width = 360;
            height = 350;
            celebrio.desktop.icons = new celebrio.icons(id,width,height);
            $.getJSON(
                getapps,
                function (data) {
                    celebrio.desktop.icons.setCols(data.length);
                    $("#desktop").css({"width" : data.length*width});
                    iScrollLoad();
                    for (var i in data) {
                        app = data[i];
                        celebrio.desktop.icons.set(new celebrio.icon("images/seniors/"+app.name+".png",app.title,app.url
                            ),i);
                    }
                    celebrio.scrollbar.init(celebrio.desktop.icons);
                    celebrio.desktop.icons.draw();
                }
        	);
        }
    },
	
	"image" : {
		resize : function(image, element) {
			proportions = {
				width : image.width,
				height : image.height
			};

			if(element.width() < image.width) {
				proportions.width = element.width();
				proportions.height = (element.width() / image.width) * image.height;
			}

			if(element.height() < image.height) {
				proportions.height = element.height();
				proportions.width = (element.height() / image.height) * image.width;
			}
			return proportions;
		},
		center : function(innerW, innerH, outerW, outerH) {
			return {
				left : ( outerW - innerW) / 2,
				top : ( outerH - innerH) / 2
			};
		},
		stretch : function(image, element) {
			image.width = element.width();
			image.height = element.height();
		}
	},
	
	"icons" : function(element, width, height) {
	this.width = width;
    this.height = height;
    this.element = element;
    this.cols = 0;
    this.icons = new Array();

    this.getWidth = function () {
        return this.width;
    };
    this.getHeight = function () {
        return this.height;
    };

    this.getCols = function () {
        return this.cols;
    };
    this.setCols = function (cols) {
        this.cols = cols;
    };

    this.draw = function () {
        this.element.find(".albireoicon").remove();
        for ( i = 0; i < this.getCols();i++) {
            if (this.get(i) != null) {
                this.get(i).element = $('<div class="albireoicon"></div>').appendTo(this.element).css(
                {
                    top: Math.max(celebrio.desktop.getHeight()/2 - this.getHeight()/2,0),
                    //top: (($(window).height()/2) - ($(".albireoicon").height()/2)),
                    left: i*this.getWidth(),
                    width: this.getWidth(),
                    height: this.getHeight()
                })
                .attr("id", this.get(i).url)
                .html('<img src="'+this.get(i).image+'" class="iconimage" /><div class="iconName"><div class="nameText">'+this.get(i).name+'</div></div>')
                .bind('click', function () {
                    if (!dragging) {
                    	
						image = $(this).clone().html();
						$("#taskspace").find("#" + $(this, ".iconName").text()).remove();
						if($(".taskItem").size() >= 5)
							$("#.taskItem:last").remove();
						
						var timer = 0;
						if($(".taskItem").size() > 0) {
							$("#taskspace").append("<div id=taskicons></div>");
							$("#taskicons").append($("#taskspace .taskItem"));
							$("#taskicons").animate({
								"left" : "+=" + $("#taskspace img").outerWidth(true)
							}, 250, "linear", function(){
								$("#taskicons").replaceWith($("#taskicons").html());
							});
							timer = 250;
						}
						
						helper = this;
						setTimeout(function(){
                        	$("#taskspace").prepend("<div id='" + $(helper, ".iconName").text() + "' class='taskItem' url='"+$(helper).attr("id")+"'>"+ image +"</div>");
                        	$("#"+$(helper, ".iconName").text()).hide().fadeIn(250);                    					
                        	$("#taskspace .iconName").hide();
                        
                        	$("#taskspace img").css({
                        		"height": ($("#taskspace").height() + 10), 
                        		"width" : "auto",
                        		"float" : "left",
                        		"margin" : "-20px 0px 0px 0px"
                        	});
                        	
                        	var iconWidth = $("#taskspace img").width();
                        	var totalWidth = $("#taskspace img").length * iconWidth;
        					$("#taskspace img").css({"marginLeft": (($("#taskspace").width() - (5*iconWidth))/10)}); 
        					$("#taskspace img").css({"marginRight": (($("#taskspace").width() - (5*iconWidth))/10)-1});
                        }, timer);	
						
                        setTimeout(function(){
                        	celebrio.applications.createFromUrl($(helper).find(".iconName").html(),$(helper).attr("id"));
                        	$(".albireoicon").fadeOut("slow");
                        	$("#taskbar").fadeOut("slow");
                        	$("#scrollbar").fadeOut("slow");
                        	$('#startbutton').fadeIn("slow");
                        
                        	$(".taskItem").click(function(){
                        		celebrio.applications.createFromUrl($(this).find(".iconName").html(),$(this).attr("url"));
                        		$(".albireoicon").fadeOut("slow");
                        		$("#taskbar").fadeOut("slow");
                        		$("#scrollbar").fadeOut("slow");
                        		$('#startbutton').fadeIn("slow");
                       		});                       
                        },250 + timer);
                    }
               });
               /* .draggable(function(){
                	drag: function(event, ui){
					$("#scroller").css({
						"left": ('-' + (ui.position.left * (moveRacio)) + "px")
					});
					}
                });*/
            }
        }
        
        $(".iconimage").css({
            'maxHeight' : this.height,
            'maxWidth': this.width
        });
    };
    
    this.resize = function () {
        this.element.find(".albireoicon").css({
            top: Math.max(celebrio.desktop.getHeight()/2 - this.getHeight()/2,0)
            });
    };

    this.set = function (icon,place) {
        this.icons[place] = icon;
    };
    this.get = function (place) {
        return this.icons[place];
    };
	},
	
	"icon" : function (image,name,url) {
        this.name = name;
        this.url = url;
        this.title = null;
        this.image = image;
        this.element = null;
	
        this.getName = function () {
            return this.name;
        };
	
        this.setName = function (name) {
            this.name = name;
        };
		
        this.getTitle = function () {
            return this.title;
        };
	
        this.setTitle = function (title) {
            this.title = title;
        };
	
        this.getImage = function () {
            return this.image;
        };
	
        this.setImage = function (image) {
            this.image = image;
        };
    },
	
	"scrollbar" : {
		"scrollerMarginSum" : 10, // sucet marginov scrollera, 5 + 5, v pripade zmeny zmenit css
		
		"moveRatio" : function(){
			return (celebrio.desktop.element.width() / ($(window).width() - celebrio.scrollbar.scrollerMarginSum));
		},
		
		"scrollerWidth" : function(){
			return ($(window).width() / celebrio.scrollbar.moveRatio());
		},
		
		"init" : function(icons){
			$("#scroller").width(celebrio.scrollbar.scrollerWidth());
			/*
			for (var i=0; i < icons.getCols(); i++) {
				$("#scrollbar").append('<img src="'+icons.get(i).image+'" id="scrollbarIcon'+i+'" class="scrollbarImage" />');
				
				$("#scrollbarIcon" + i).css({
            		width: "87px",
                	height: "70px",
                	zIndex: 2001,
                	marginTop: "5px",
                	marginBottom: "5px",
                	opacity: "0.7"
            	});
			};
			
            var iconsWidth = (icons.getCols() * $(".scrollbarImage").width());
			var marginWidth = ($(window).width() - iconsWidth) /  (icons.getCols() * 2);
            
			$(".scrollbarImage").css({
				marginLeft: marginWidth,
				marginRight: marginWidth
			});
			*/
			$("#scroller").draggable({
            	axis : 'x',           
                distance : 30,
                containment : "parent",
                drag: function(event, ui){
					$("#desktop").css({
						"MozTransform": "translate(" + ('-'+(ui.position.left * (celebrio.scrollbar.moveRatio())))+ "px, 0px)",
						"WebkitTransform": "translate3d(" + ( '-'+(ui.position.left * (celebrio.scrollbar.moveRatio())))+ "px, 0px, 0px)",
						"left": ( '-'+(ui.position.left * (celebrio.scrollbar.moveRatio())))+ "px"
					});
				}
            });
            
            $("#scrollbar").click(function(e){
       			var x = e.pageX;
        		var scrollerPosition;
        		
        		if ((($("#scroller").width() / 2) + x) > ($("#scrollbar").width() - celebrio.scrollbar.scrollerMarginSum)) {			
        			scrollerPosition = $("#scrollbar").width() - celebrio.scrollbar.scrollerMarginSum -  ($("#scroller").width() /2);
        		} else if((x - (($("#scroller").width() / 2)) < celebrio.scrollbar.scrollerMarginSum)){
        			scrollerPosition = $("#scroller").width() /2;
        		} else {
        			scrollerPosition = x;
        		}
        			
        		$("#scroller").animate({
					"left" : "+=" + (scrollerPosition - $("#scroller").position().left - ($("#scroller").width() / 2))
				}, {
					duration : 250,
					easing : "linear", 
  					step : function(){
    					$("#desktop").css({
						"MozTransform": "translate(" + ('-'+($("#scroller").position().left * (celebrio.scrollbar.moveRatio())))+ "px, 0px)",
						"WebkitTransform": "translate3d(" + ( '-'+($("#scroller").position().left * (celebrio.scrollbar.moveRatio())))+ "px, 0px, 0px)",
						"left": ( '-'+($("#scroller").position().left * (celebrio.scrollbar.moveRatio())))+ "px"
					});
  					},
  					complete : function(){
    					$("#desktop").css({
						"MozTransform": "translate(" + ('-'+($("#scroller").position().left * (celebrio.scrollbar.moveRatio())))+ "px, 0px)",
						"WebkitTransform": "translate3d(" + ( '-'+($("#scroller").position().left * (celebrio.scrollbar.moveRatio())))+ "px, 0px, 0px)",
						"left": ( '-'+($("#scroller").position().left * (celebrio.scrollbar.moveRatio())))+ "px"
					});
  					}
   				}); 
			});
			/*
			$('.scrollbarImage').mousedown(function(e){
				e.preventDefault();
			})
			$('#scrollbar').delegate("img", "mousedown", function(e){
				var position = e.pageX;
				
				if(position >= $('#scroller').position().left && position <= $('#scroller').position().left + $('#scroller').width())
					$('#scroller').trigger(e);
			});
			*/
		},
		
		"resize" : function() {
			/*
			var iconsWidth = ($(".scrollbarImage").length * $(".scrollbarImage").width());
			var marginWidth = ($(window).width() - iconsWidth) /  ($(".scrollbarImage").length * 2);
            
			$(".scrollbarImage").css({
				marginLeft: marginWidth,
				marginRight: marginWidth
			});
			*/
			$("#scroller").width(celebrio.scrollbar.scrollerWidth());
			if($("#scroller").position().left + celebrio.scrollbar.scrollerWidth() > $(window).width() - 10)
				$("#scroller").css({
					"left" : ($(window).width() - 10 - celebrio.scrollbar.scrollerWidth())
				});
		}
	},
	
	"taskbar" : {
		"element" : null,
		"setElement" : function(element) {
			celebrio.taskbar.element = element;
		},
		"getElement" : function() {
			return celebrio.taskbar.element;
		},
		"start" : {
			"element" : null,
			"image" : null,
			"caption" : null,
			"getElement" : function() {
				return celebrio.taskbar.start.element;
			},
			"setElement" : function(element) {
				celebrio.taskbar.start.element = element;
			},
			"getImage" : function() {
				return celebrio.taskbar.start.image;
			},
			"setImage" : function(image) {
				celebrio.taskbar.start.image = image;
			},
			"getCaption" : function() {
				return celebrio.taskbar.start.caption;
			},
			"setCaption" : function(caption) {
				celebrio.taskbar.start.caption = caption;
			},
			"draw" : function() {
				id = celebrio.taskbar.start.getElement();
				id.html(
				celebrio.taskbar.start.getImage() ? "<div id='taskbarstartimage'><img src='"+celebrio.taskbar.start.getImage()+"' alt='start image'/></div>" : "" +
				celebrio.taskbar.start.getCaption() ? "<div id='taskbarstartcaption'>"+celebrio.taskbar.start.getCaption()+"</div>" : ""
				).mousedown(function() {
					$(".dialogApplication").dialog("minimize");
					$(".albireoicon").fadeIn("slow");
					$("#taskbar").fadeIn("slow");
					$("#scrollbar").fadeIn("slow");
					$('#startbutton').fadeOut("slow");
				});
			}
		},
		"draw" : function() {
			celebrio.taskbar.start.draw();
		}
	},
	
	"applications" : {
        APPLICATION : "application",
        pid : 0,
        processes : [],
        listeners : [],
        focus: null,
        moveToVisible : function () {
            if ($(".ui-dialog").position().top < 0 ) {
                $(".ui-dialog").css(top, 0);
            }
        },
        kill : function (process) {
            $("#"+celebrio.applications.APPLICATION+process.getId()).remove();
            celebrio.arrays.remove(process,celebrio.applications.processes);
        },
        setFocus : function (process) {
            if (process == null) {
                celebrio.applications.focus = null;
                return;
            }
            if(process.isWindowed()){
                celebrio.applications.focus = process;
            }
        },
        addAppListener : function (listener) {
            celebrio.applications.listeners.push(listener);
        },
        removeAppListener : function (listener) {
            celebrio.arrays.remove(listener, celebrio.applications.listeners);
        },
        addProcess : function (process) {
            celebrio.applications.processes.push(process);
        },
        removeProcess : function (process) {
            celebrio.arrays.remove(process, celebrio.applications.processes);
        },
        create : function (name, windowed) {
            if (!windowed) {
                windowed = false;
            }
            process = new celebrio.applications.process(celebrio.applications.newPid());
            process.setName(name);
            process.setWindowed(windowed);
            celebrio.applications.addProcess(process);
            for (var listener in celebrio.applications.listeners) {
                celebrio.applications.listeners[listener].create(process);
            }
            return process;
        },
        createSingle : function(name, windowed) {
			for(var i in celebrio.applications.processes) {
				if(celebrio.applications.processes[i].getName() == name) {
					celebrio.applications.processes[i].toggle();
					return null;
				}
			}
			return celebrio.applications.create(name, windowed);
		},
		createWindow : function(name, content, options) {
			if(options == undefined) {
				options = {};
			}
			var process = celebrio.applications.createSingle(name, true);
			if(process != null) {
				var app = $("<div id='"+celebrio.applications.APPLICATION+process.getId()+"' class='dialogApplication' title='"+name+"'>"+content+"</div>").appendTo($("#desktopWrapper"))
				.dialog({
					minimizable : true,
					maximized : true,
					//TODO: ADD users before close to handle close button (for saving and so on) event listener
					focus : process.focus,
					close : process.close,
					resizable : false,
					draggable : false
				});
				$(app).find('.resizable').width($(app).width()).height($(app).height());

				$('.ui-dialog-titlebar-maxi').click(function() {
					$('#'+celebrio.applications.APPLICATION+process.getId()).focus();
				});
				celebrio.applications.focused = process;
			}
		},
        createGadget : function (name,content,options) {
            if (options == undefined) {
                options = {};
            }
            process = celebrio.applications.create(name);
            process.setWindowed(true);

            //TODO: oklestena verze options - melo by se vytvorit, obecnejsi a nakej obecnej parser kerej bude jen predavat
            var app = $("<div id='"+celebrio.applications.APPLICATION+process.getId()+"' title='"+name+"'>"+content+"</div>").appendTo($("body")).draggable().css({
                width: (options.width ? options.width : 177),
                height: (options.height ? options.height : 'auto'),
                position: "absolute",
                left: (options.position ? options.position.left : 100),
                top: (options.position ? options.position.top : 0)
            //backgroundColor: "#fff"
            }).resizable({
                resize: function () {
                    $(this).find('.resizable').width($(this).width()-5).height($(this).height()-5);
                }
            });
            //alert($(app).find('.resizable').attr('src'));
            $(app).find('.resizable').width($(app).width()-5).height($(app).height()-5);

            $("<a href='#' class='ui-dialog-titlebar-close'><span class='ui-icon ui-icon-closethick'></a>").bind( 'click', process.close ).css({
                position: "absolute",
                display: "block",
                "float":"right",
                backgroundColor: "#bbb",
                right: 0,
                top: 0,
                width: "16px"
            }).appendTo(app);

        //app.hover(function() { closeButton.prependTo(app); }, function () { closeButton.remove(); });
        },
        createFromHtml : function(name,html,options) {
            celebrio.applications.createWindow(name,html,options);
        },
        createFromUrl : function(name,url,options) {
            celebrio.applications.createFromHtml(name,"<iframe src='"+url+"' class='resizable' />",options);
        },
        resize : function (app) {
        //TODO: after presentation
        },
        //TODO: temporary solution!
        process : function (id) {
            this.id = id;
            this.name = null;
            this.windowed = false;
            this.focus = false;
            var self = this;
			
            this.equals = function(process) {
                //TODO: should take care that object is really process type - better type recognition
                if (process == null ) return false;
                if (this.getId() === process.getId()) {
                    return true;
                }
                return false;
            };
	
            this.getId = function () {
                return this.id;
            };
		
            this.getName = function () {
                return this.name;
            };
	
            this.setName = function (name) {
                this.name = name;
            };
			
            this.isWindowed = function () {
                return this.windowed;
            };
			
            this.setWindowed = function(windowed) {
                this.windowed = windowed;
            };

            //TODO: should this have any application? some of them are not windowed or can be gadgets...
            //Window can  be observer of process
            this.toggle = function () {
                //TODO: shouldnt be done by dialogs attributes??? More information than really needed OR delegation to "Window"
                if (self.isWindowed()) {
                    if (self.equals(celebrio.applications.focus)) {
                        $("#"+celebrio.applications.APPLICATION+self.getId()).dialog("minimize");
                        celebrio.applications.setFocus(null);
                    } else {
                        $("#"+celebrio.applications.APPLICATION+self.getId()).dialog("unminimize");
                        celebrio.applications.setFocus(self);
                    }
                }
            };

            this.focus = function () {
                celebrio.applications.setFocus(self);
            };

            this.close = function() {
                for (var listener in celebrio.applications.listeners) {
                    celebrio.applications.listeners[listener].close(self);
                }
			
                //TODO: maybe also an observer
                if (self.isWindowed()) {
                    $("#"+celebrio.applications.APPLICATION+self.getId()).remove();
                }
                celebrio.applications.removeProcess(self);
                //TODO: always return false to prevent link or event stop propagation?
                return false;
            };
        },
        newPid : function () {
            return ++celebrio.applications.pid;
        }
    },
    
	"arrays" : {
        find : function(what, where) {
            if (what == null) {
                return false;
            }
            for (var i in where) {
                if (what.equals(where[i])) {
                    return i;
                }
            }
            return false;
        },
		
        remove : function(what, where)  {

            which = celebrio.arrays.find(what, where);
            if (which) {
                where.splice(which, 1);
            }
        }
   },
    
	"keys" : {
		"ctrl" : false,
		"init" : function() {
			$(document).keydown(function(event) {
		 		if (event.ctrlKey) {
					celebrio.keys.ctrl = true;
				}	
			}).keyup(function(event) {
				if(event.which == 17) {
					celebrio.keys.ctrl = false;
				}
			});
		}
	}
}

initfnc = function () {
    if (typeof document.body.onselectstart!="undefined")
	document.body.onselectstart=function(){ return false }
    else if (typeof document.body.style.MozUserSelect!="undefined")
	document.body.style.MozUserSelect="none";

    var url = "images/seniors/wall.jpg";
    celebrio.taskbar.setElement($("#taskbarmini"));
    celebrio.taskbar.start.setElement($("#startbutton"));
    celebrio.taskbar.start.setImage("systemApps/shared/start_button.png");
    celebrio.taskbar.draw();

    celebrio.desktop.setElement($("#desktop"));
    celebrio.desktop.setColor("#000");
    celebrio.desktop.display(url);
    celebrio.desktop.createIcons();
    celebrio.keys.init();
	
    $(window).resize( function () {
    	celebrio.scrollbar.resize();
        celebrio.desktop.display(url);
        id = celebrio.desktop.getElement();
        id.height($(window).height());
        celebrio.desktop.icons.resize();
        $(".dialogApplication iframe").css({"height" : $(window).height(), "width" : $(window).width()});
        $(".dialogApplication").dialog("maximize");      
    });
    $(window).load( function () {
        $("#loading").remove();
    });
}

$(document).ready(initfnc);